package praktikumid.w10.p4;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.util.ArrayList;
import java.util.List;

import javax.swing.JPanel;

public class DrawPanel extends JPanel {
	
	private List<Shape> shapes = new ArrayList<Shape>();
	
	Shape highlightedShape = null;
	
	class DrawListener extends MouseAdapter implements KeyListener {
		@Override
		public void mouseDragged(MouseEvent e) {
			if ((e.getModifiers() & MouseEvent.BUTTON3_MASK) == MouseEvent.BUTTON3_MASK) {
				selectClosestShape(e.getPoint());
			} else {
				getLastShape().mouseDragged(e);
			}
			repaint();
		}
		
		@Override
		public void mouseClicked(MouseEvent e) {
			getLastShape().mouseClicked(e);
			repaint();
		}
		
		@Override
		public void mouseReleased(MouseEvent e) {
			getLastShape().mouseReleased(e);
		}

		@Override
		public void keyPressed(KeyEvent e) {
			if (e.getKeyCode() == KeyEvent.VK_LEFT) {
				if (highlightedShape != null) {
					highlightedShape.move(-10, 0);
					repaint();
				}
			}
			
		}

		@Override
		public void keyReleased(KeyEvent arg0) {
			// TODO Auto-generated method stub
			
		}

		@Override
		public void keyTyped(KeyEvent arg0) {
			// TODO Auto-generated method stub
			
		}
	}
	
	public DrawPanel() {
		setBackground(Color.WHITE);
		
		shapes.add(new Rectangle());
		
		DrawListener l = new DrawListener();
		addMouseListener(l);
		addMouseMotionListener(l);
		addKeyListener(l);
		
		setFocusable(true);
		requestFocus();
	}
	
	public void selectClosestShape(Point p) {
		int minDistance = Integer.MAX_VALUE;
		Shape closestShape = null;
		for (Shape s : shapes) {
			int d = s.getDistance(p);
			if (d < minDistance) {
				minDistance = d;
				closestShape = s;
			}
		}
		
		highlightedShape = closestShape;
		for (Shape s : shapes) {
			if (s == closestShape) {
				s.setHighlighted(true);
			} else {
				s.setHighlighted(false);				
			}
		}
		
	}
	
	public Shape getLastShape() {
		
		/*
		 * on click:
		 * PRESSED - empty
		 * RELEASED
		 * CLICKED
		 * 
		 * on drag:
		 * (PRESSED)
		 * DRAG
		 * 
		 * (RELEASE)
		 */
		
		if (shapes.size() == 0 ||
				shapes.get(shapes.size() - 1).isFinished()) {
			//Shape s = new Rectangle();
			Shape s = new Polygon();
			shapes.add(s);
		}
		return shapes.get(shapes.size() - 1);
	}
	
	@Override
	protected void paintComponent(Graphics g) {
		super.paintComponent(g);
		
		for (Shape s : shapes) {
			s.paintComponent(g);
		}
	}
}
